package com.tczs.server.request;

import com.tczs.server.Config;
import com.tczs.server.SunChannelInitializer;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractServerBuildRequestSwap extends AbstractServerBuildRequest{
    private static Logger logger = Logger.getLogger(AbstractServerBuildRequestSwap.class);

    @Override
    public ServerRequestModel getParamFromFirstLine(ServerRequestModel request) {
        String allUrl = request.getUrl();
        try {
            allUrl = URLDecoder.decode(allUrl,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("decode url failed",e);
        }
        Object params = null;
        if (allUrl.contains("?")) {
            String url = allUrl.substring(0, allUrl.indexOf("?"));
            request.setUrl(url);
            params = allUrl.substring(allUrl.indexOf("?") + 1);
        } else {
            request.setUrl(allUrl);
        }
        request = getParamFromMethod(request,request.getMethod(),params);
        return request;
    }

    @Override
    public ServerRequestModel getParamFromMethod(ServerRequestModel request,String method,Object obj){
      //  logger.info(obj.toString());
        Map<String,Object> params = null;
        switch (method){
            case "GET":
                params = Config.getGetMethodBuildParameter().buildParameter((String) obj);
                break;
            case "OPTIONS":
                break;
            default:
                throw new IllegalStateException("no BuildParameter mapping");
        }
        request.setParams(params);
        return request;
    }

    @Override
    public ServerRequestModel completeRequest(ServerRequestModel request,String[] array) {
        for(String line : array) {
            if (line == null || line.length() == 0) {
                return request;
            } else {
                if (line.startsWith("X-real-ip:")) {
                    String ip = line.substring("X-real-ip:".length() + 1);
                    request.setRemoteHost(ip);
                    Map<String, Object> params = request.getParams();
                    if (params == null) {
                        params = new HashMap<>();
                        params.put("ip", ip);
                        request.setParams(params);
                    } else {
                        params.put("ip", ip);
                    }
                } else if (line.startsWith("User-Agent:")) {
                    request.setUserAgent(line.substring("User-Agent:".length() + 1));
                }else if (line.startsWith("token:")) {
                    request.setToken(line.substring("token:".length() + 1));
                } else {
                }
            }
        }
        return request;
    }

}
